package charpter13.lynx;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.mindview.util.TextFile;

public class Sixteen {
	public static void main(String[] args) throws Exception {
		if (args.length < 2) {
			System.out.println("Usage: java JGrep file regex");
			System.exit(0);
		}
		
		File[] files = new File(args[0]).listFiles();
		
		Pattern p = Pattern.compile(args[1]);
		
		if (files == null){
			
			// Iterate through the lines of the input file:
			grep(args[0], p);
		}else{
			for (File file:files){
				grep(file.getAbsolutePath(), p);
			}
		}
		
		
	}

	private static void grep(String filename, Pattern p) {
		int index = 0;
		Matcher m = p.matcher("");
		for (String line : new TextFile(filename)) {
			m.reset(line);
			while (m.find())
				System.out.println(index++ + ": " + m.group() + ": "
						+ m.start());
		}
	}
}
